import os
from odps import ODPS
from tools.lbs_utils import *

"""
检查路程时间
"""

odps = ODPS('xxx', 'xxxxxxxxxxx', 'xxx_APP', endpoint='http://service.odps.aliyun.com/api')

if __name__ == '__main__':
    for i in range(1, 30):
        over_2h_travel = []
        sel_day = get_yesterday(i)
        sel_ds = get_yesterday(i, '%Y%m%d')
        target_file = 'data/orders_' + sel_day + '.csv'
        if not os.path.exists(target_file):
            sql_orders = """
            select * from xxx_ods.dws_th_user_order_detail
             where ds='%s' and substr(reserve_tm,1,10)='%s' and order_status_cd='用户处理完成'
            """ % (sel_ds, sel_day)
            with odps.execute_sql(sql_orders).open_reader() as reader:
                result_df = reader.to_pandas()
            result_df['location'] = result_df['srv_addr'].apply(geo_to_location)
            result_df.sort_values('reserve_tm', inplace=True)
            print(sel_day, result_df.shape)
            result_df.to_csv(target_file)
        else:
            result_df = pd.read_csv(target_file)

        target_file1 = 'data/over_' + sel_day + '.csv'
        if not os.path.exists(target_file1):
            artisan_ids = result_df['artisan_id'].drop_duplicates()
            for artisan_id in artisan_ids:
                artisan_orders = result_df[result_df['artisan_id']==artisan_id]
                prev_order = None
                for i in range(len(artisan_orders)):
                    artisan_order = artisan_orders.iloc[i]
                    if prev_order is not None:
                        start_time = get_start_hour(artisan_order['reserve_tm'])
                        if artisan_order['location'] is not None:
                            artisan_order['travel_time'], artisan_order['distance'] = city_location_to_time(prev_order['location'], artisan_order['location'], prev_order['city_name'], start_time, artisan_order['city_name'])
                            # if artisan_order['travel_time'] > 2 * 60 * 60:
                            over_2h_travel.append(artisan_order)
                    if artisan_order['location'] is not None:
                        prev_order = artisan_order

            df_over = pd.DataFrame(over_2h_travel)
            print(sel_day, df_over.shape)
            df_over.to_csv(target_file1)
